//
//  IWTextView.m
//  liangyi
//
//  Created by 张水 on 16/12/26.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "IWTextView.h"
#import "UIView+Extension.h"

@interface IWTextView()<UITextViewDelegate>

@property (nonatomic, strong) UILabel *placeholderLable;


@end

@implementation IWTextView


- (UILabel *)placeholderLable{
    if (!_placeholderLable) {
        //添加占位文字的label
        UILabel *placeholderLable = [[UILabel alloc] init];
        placeholderLable.textColor = [UIColor lightGrayColor];
        placeholderLable.font = self.font;
        placeholderLable.numberOfLines = 0;
        [self addSubview:placeholderLable];
        [placeholderLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.mas_centerY);
            make.left.equalTo(self).offset(10);
        }];
        _placeholderLable = placeholderLable;
    }
    return _placeholderLable;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.font = [UIFont systemFontOfSize:15];
        
    }
    return self;
}


- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    //设置文字
    self.placeholderLable.text = placeholder;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    
    //设置占位文字的位置
    self.placeholderLable.x = 5;
    self.placeholderLable.y = 8;
    
    //设置大小
//    self.placeholderLable.size = [self.placeholderLable.text sizeWithFont:self.placeholderLable.font constrainedToSize:CGSizeMake(self.width - 10, MAXFLOAT)];
    self.placeholderLable.frame = [self.placeholderLable.text boundingRectWithSize:CGSizeMake(self.width -10, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
}

- (void)textDidChange{
    self.placeholderLable.hidden = self.text.length;
}

- (void)setFont:(UIFont *)font{
    [super setFont:font];
    //去调整placeholder的字体大小
    self.placeholderLable.font = font;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
